import { defineStore } from 'pinia'

// 用户存储VO
export const useUserStore = defineStore('user', {
  state: () => {
    // 从localStorage获取用户数据
    const storedUserData = localStorage.getItem('user')
    let initialState = {
      // JWT令牌
      authorization: '',
      // 用户ID
      id: 0,
      // 手机号
      phone: '',
      // 邮箱
      email: '',
      // 昵称
      nickName: '',
      // 头像
      avatar: '',
      // 状态
      status: 0,
      // 创建时间
      createTime: '',
      // 更新时间
      updateTime: ''
    }
    
    // 如果localStorage中有用户数据，则使用存储的数据
    if (storedUserData) {
      try {
        const parsedData = JSON.parse(storedUserData)
        initialState = {
          authorization: parsedData.authorization || '',
          id: parsedData.id || 0,
          phone: parsedData.phone || '',
          email: parsedData.email || '',
          nickName: parsedData.nickName || '',
          avatar: parsedData.avatar || '',
          status: parsedData.status || 0,
          createTime: parsedData.createTime || '',
          updateTime: parsedData.updateTime || ''
        }
      } catch (error) {
        console.error('解析localStorage用户数据失败:', error)
      }
    }
    
    return initialState
  },

  getters: {
    isLoggedIn: (state) => !!state.authorization,
    userInfo: (state) => ({
      id: state.id,
      phone: state.phone,
      email: state.email,
      nickName: state.nickName,
      avatar: state.avatar,
      status: state.status,
      createTime: state.createTime,
      updateTime: state.updateTime
    })
  },

  actions: {
    // 设置用户信息
    setUserInfo(userData) {
      this.authorization = userData.authorization || ''
      this.id = userData.id || 0
      this.phone = userData.phone || ''
      this.email = userData.email || ''
      this.nickName = userData.nickName || ''
      this.avatar = userData.avatar || ''
      this.status = userData.status || 0
      this.createTime = userData.createTime || ''
      this.updateTime = userData.updateTime || ''
      
      // 同时保存到localStorage
      const userInfo = {
        authorization: this.authorization,
        id: this.id,
        phone: this.phone,
        email: this.email,
        nickName: this.nickName,
        avatar: this.avatar,
        status: this.status,
        createTime: this.createTime,
        updateTime: this.updateTime
      }
      localStorage.setItem('user', JSON.stringify(userInfo))
    },

    // 清除用户信息
    clearUserInfo() {
      this.authorization = ''
      this.id = 0
      this.phone = ''
      this.email = ''
      this.nickName = ''
      this.avatar = ''
      this.status = 0
      this.createTime = ''
      this.updateTime = ''
      
      // 同时清除localStorage中的用户数据
      localStorage.removeItem('user')
    }
  }
})